<template>
  <div class="profile-container">
    <a-space direction="vertical" style="width: 100%">
      <!-- 個人信息簡介 -->
      <a-card class="profile-info-card">
        <div style="text-align: center">
          <h3>{{ userInfo.username }}</h3>
        </div>
        <a-flex justify="space-evenly" align="center">
          <div>
            角色:
            <a-button
              size="small"
              type="text"
              v-for="role in userInfo.roles"
              :key="role"
              >{{ role }}</a-button
            >
          </div>
          <div v-if="userInfo.email">Email: {{ userInfo.email }}</div>
          <template v-if="userInfo.extra.staffCode">
            <div>員工編號:{{ userInfo.extra.staffCode }}</div>
            <div>
              醫師類型:{{ userInfo.extra.type == 1 ? "合作醫師" : "職員醫師" }}
            </div>
            <div>
              駐診形式: {{ userInfo.extra.shiftType == 1 ? "半日" : "全日" }}
            </div>
          </template>
        </a-flex>
      </a-card>

      <!-- 我的佣金 -->
      <a-card
        title="當月銷售統計"
        :loading="salesLoading"
        v-if="userInfo.roles.includes('Doctor')"
      >
        <template #extra
          ><small class="update-time"
            >數據更新日期：{{ latestDate }}</small
          ></template
        >
        <a-flex justify="space-between" align="center" style="height: 60px">
          <a-space size="middle">
            <a-typography-text strong style="font-size: 16px">
              <span v-if="curDateType == 'date'">日期</span>
              <span v-else>月份</span>
              : {{ commStatPeriod }}
            </a-typography-text>
            <a-button
              size="small"
              type="primary"
              shape="round"
              @click="showModal"
              >更改</a-button
            >
          </a-space>
          <Router-link
            v-if="curDateType == 'month' && router.hasRoute('CommissionList')"
            :to="{
              name: 'CommissionList',
              query: { stat_month: commStatPeriod },
            }"
            >查看該月佣金詳情
          </Router-link>
        </a-flex>

        <a-row>
          <a-col span="6">
            <a-card>
              <a-statistic
                title="總銷售額"
                :value="curSaleStat.invoiceNet"
                prefix="$"
              />
            </a-card>
          </a-col>
          <a-col span="5">
            <a-card>
              <a-statistic
                title="診症數"
                :value="curSaleStat.consultCount"
                prefix=""
                suffix="個"
              />
            </a-card>
          </a-col>
          <a-col span="4">
            <a-card>
              <a-statistic
                title="非診症數"
                :value="curSaleStat.nonConsultCount"
                prefix=""
                suffix="個"
              />
            </a-card>
          </a-col>
          <a-col span="5">
            <a-card>
              <a-statistic
                title="開單數"
                :value="curSaleStat.invoiceCount"
                prefix=""
                suffix="單"
              />
            </a-card>
          </a-col>
          <a-col span="4">
            <a-card>
              <a-statistic
                title="退單數"
                :value="curSaleStat.refundCount"
                prefix=""
                suffix="單"
              />
            </a-card>
          </a-col>
        </a-row>
        <a-divider orientation="left">附加項目</a-divider>
        <a-row>
          <a-col span="5">
            <a-card>
              <a-statistic
                title="套票銷售額"
                :value="curSaleStat.packageAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>

          <a-col span="5">
            <a-card>
              <a-statistic
                title="針灸銷售額"
                :value="curSaleStat.apAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>
          <a-col span="4">
            <a-card>
              <a-statistic
                title="針灸次數"
                :value="curSaleStat.apCount"
                prefix=""
                suffix="次"
              />
            </a-card>
          </a-col>

          <a-col span="5">
            <a-card>
              <a-statistic
                title="天灸銷售額"
                :value="curSaleStat.tpAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>

          <a-col span="4">
            <a-card>
              <a-statistic
                title="天灸次數"
                :value="curSaleStat.tpCount"
                prefix=""
                suffix="次"
              />
            </a-card>
          </a-col>
        </a-row>
        <a-divider orientation="left">常規銷售</a-divider>
        <a-row>
          <a-col span="6">
            <a-card>
              <a-statistic
                title="處方銷售額"
                :value="curSaleStat.cmAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>

          <a-col span="6">
            <a-card>
              <a-statistic
                title="蟲草銷售額"
                :value="curSaleStat.cyAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>

          <a-col span="6">
            <a-card>
              <a-statistic
                title="燕窩銷售額"
                :value="curSaleStat.neAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>
        </a-row>
        <a-divider orientation="left">附加推廣</a-divider>
        <a-row>
          <a-col span="6">
            <a-card>
              <a-statistic
                title="安宮銷售額"
                :value="curSaleStat.agAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>

          <a-col span="6">
            <a-card>
              <a-statistic
                title="本廠銷售額"
                :value="curSaleStat.wytAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>

          <a-col span="6">
            <a-card>
              <a-statistic
                title="OEM銷售額"
                :value="curSaleStat.oemAmount"
                prefix="$"
                suffix=""
              />
            </a-card>
          </a-col>
        </a-row>
      </a-card>

      <!-- 我的獎金 -->
      <a-card
        title="我的獎金"
        :loading="bonusLoading"
        v-if="userInfo.roles.includes('Doctor')"
      >
        <template #extra
          ><small class="update-time"
            >數據更新日期：{{ latestDate }}</small
          ></template
        >
        <a-flex justify="space-between" align="center" style="height: 50px">
          <a-space size="middle">
            <a-typography-text strong style="font-size: 16px">
              <span>月份</span>
              : {{ bonusStatMonth }}
            </a-typography-text>
            <a-button
              size="small"
              type="primary"
              shape="round"
              @click="
                {
                  openBonus = true;
                  selectedBonusMonth = bonusStatMonth;
                }
              "
              >更改</a-button
            ></a-space
          >
          <Router-link
            v-if="router.hasRoute('BonusList')"
            :to="{
              name: 'BonusList',
              query: { stat_month: commStatPeriod },
            }"
            >查看該月獎金詳情
          </Router-link>
        </a-flex>
        <a-row :gutter="16">
          <template v-if="bonusList.length === 0">
            <a-empty style="width: 100%" />
          </template>
          <a-col v-for="(item, index) in bonusList" :key="index">
            <a-card
              style="width: 300px"
              :headStyle="{ backgroundColor: '#f0f2f5' }"
              hoverable
            >
              <template #title>
                <a-flex justify="center" align="flex-end">
                  <a-typography-title :level="5">{{
                    item.bonusName
                  }}</a-typography-title>
                </a-flex>
              </template>
              <a-space direction="vertical">
                <span>月份：{{ item.statMonth }}</span>
                <span>時間：{{ item.startDate }}~{{ item.endDate }}</span>
                <span
                  >指定產品總銷售額：$
                  {{ item.totalSalesAmount.toLocaleString() }}</span
                >
                <span
                  >距離下一指標差額：$
                  {{ item.gapAmount.toLocaleString() }}</span
                >
                <!-- <span>指定產品：TeamA，TeamC</span> -->
                <span>狀態:{{ item.isArchived ? "已歸檔" : "未歸檔" }}</span>
              </a-space>
              <a-divider style="border-color: #ccc" dashed />
              <a-flex justify="center">
                <span>可獲獎金：$ {{ item.bonusAmount.toLocaleString() }}</span>
              </a-flex>
              <!-- <template #actions>
            <a-flex justify="center">
              <span>可獲獎金：$10000</span>
            </a-flex>
          </template> -->
            </a-card>
          </a-col>
        </a-row>
      </a-card>
    </a-space>
  </div>
  <a-modal v-model:open="open" title="銷售統計" :footer="null" width="380px">
    <a-flex justify="center">
      <a-space :size="12" style="height: 80px">
        <a-select v-model:value="commStatParams.dateType">
          <a-select-option value="date">日期</a-select-option>
          <!-- <a-select-option value="week">Week</a-select-option> -->
          <a-select-option value="month">月份</a-select-option>
          <!-- <a-select-option value="year">Year</a-select-option> -->
        </a-select>
        <a-date-picker
          :picker="commStatParams.dateType"
          v-model:value="selectedStatDate"
        />
        <a-button type="primary" @click="comfirmCommDate">確認</a-button>
      </a-space>
    </a-flex>
  </a-modal>

  <a-modal
    v-model:open="openBonus"
    title="獎金查詢"
    :footer="null"
    width="380px"
  >
    <a-flex justify="center">
      <a-space :size="12" style="height: 80px">
        <a-date-picker
          picker="month"
          v-model:value="selectedBonusMonth"
          valueFormat="YYYY-MM"
        />
        <a-button type="primary" @click="comfirmBonusMonth">確認</a-button>
      </a-space>
    </a-flex>
  </a-modal>
</template>

<script lang="ts" setup>
import { useAuthUserStore } from "@/store/authUserStore";
import { ref, reactive, onMounted } from "vue";
import { personalApi } from "@/api";
import dayjs, { Dayjs } from "dayjs";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";

const router = useRouter();

const authUserStore = useAuthUserStore();
const userInfo = authUserStore.userInfo;

const latestDate = ref("");
const commStatPeriod = ref("");

const bonusList = ref([]);

const curSaleStat = reactive({
  invoiceNet: 0,
  consultCount: 0,
  nonConsultCount: 0,
  invoiceCount: 0,
  refundCount: 0,
  packageAmount: 0,
  apAmount: 0,
  apCount: 0,
  tpAmount: 0,
  tpCount: 0,
  cmAmount: 0,
  cyAmount: 0,
  neAmount: 0,
  agAmount: 0,
  wytAmount: 0,
  oemAmount: 0,
});

const salesLoading = ref(false);
const selectedStatDate = ref<Dayjs>();

const fetchInfo = async () => {
  salesLoading.value = true;
  bonusLoading.value = true;
  try {
    const { data } = await personalApi.getPersonalInfo();
    if (userInfo.roles.includes("Doctor")) {
      latestDate.value = data.latestDate;
      commStatPeriod.value = data.commStatPeriod;
      selectedStatDate.value = dayjs(data.commStatPeriod, "YYYY-MM");
      bonusStatMonth.value = data.bonusStatMonth;
      Object.assign(curSaleStat, data.invoiceStat);

      bonusList.value = data.bonusList;
    }
  } catch (error) {
    console.error("獲取信息失敗", error);
  } finally {
    salesLoading.value = false;
    bonusLoading.value = false;
  }
};

onMounted(() => {
  fetchInfo();
});

const curDateType = ref<any>("month");
const commStatParams = reactive({
  dateType: "month",
  period: "",
});
const comfirmCommDate = async () => {
  salesLoading.value = true;
  try {
    if (commStatParams.dateType == "date") {
      commStatParams.period = selectedStatDate.value.format("YYYY-MM-DD");
    } else if (commStatParams.dateType == "month") {
      commStatParams.period = selectedStatDate.value.format("YYYY-MM");
    } else {
      message.error("請選擇日期類型");
      return;
    }
    if (userInfo.roles.includes("Doctor")) {
      const { data } = await personalApi.getPersonalSaleStat(commStatParams);
      commStatPeriod.value = data.commStatPeriod;
      curDateType.value = commStatParams.dateType;
      Object.assign(curSaleStat, data.invoiceStat);
    }
  } catch (error) {
    console.error("獲取信息失敗", error);
  } finally {
    salesLoading.value = false;
    open.value = false;
  }
};
const showModal = () => {
  open.value = true;
};

const open = ref<boolean>(false);
const openBonus = ref<boolean>(false);
const bonusLoading = ref(false);

const selectedBonusMonth = ref("");
const bonusStatMonth = ref("");
const comfirmBonusMonth = async () => {
  bonusLoading.value = true;
  try {
    if (userInfo.roles.includes("Doctor")) {
      const { data } = await personalApi.getPersonalDoctorBonus({
        statMonth: selectedBonusMonth.value,
      });
      bonusStatMonth.value = data.bonusStatMonth;
      bonusList.value = data.bonusList;
    }
  } catch (error) {
    console.error("獲取獎金數據失敗", error);
  } finally {
    bonusLoading.value = false;
    openBonus.value = false;
  }
};
</script>

<style scoped>
.profile-info-card {
  /* 設置淡藍漸變色背景 */
  background: linear-gradient(135deg, #bbdefb, #e3f2fd);
}
</style>
